﻿using AutoMapper;
using Basic.Traceability.Domain.Products;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Write.Application.Command.Products.TraceableProducts;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;
using Yitter.IdGenerator;

namespace Basic.Traceability.Host.Api.Write.Application.Handler.Products.TraceableProducts
{
    public class CreateTraceableProductsHandler : IRequestHandler<CreateTraceableProductsCommand, APIResult<int>>
    {
        private readonly IBaseRepository<TraceableProductsModel> tracebleProductRepository;
        private readonly IMapper mapper;
        private readonly ILogger<CreateTraceableProductsHandler> logger;

        public CreateTraceableProductsHandler(IBaseRepository<TraceableProductsModel> tracebleProductRepository, IMapper mapper, ILogger<CreateTraceableProductsHandler> logger)
        {
            this.tracebleProductRepository = tracebleProductRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 添加商品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<int>> Handle(CreateTraceableProductsCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();
            var model = mapper.Map<TraceableProductsModel>(request);
            model.Id=YitIdHelper.NextId();

            var r = tracebleProductRepository.Create(model);
            if(r>0)
            {
                res.Msg="添加商品信息成功";
                res.Data = r;
                res.Code = APIEnums.Success;
                logger.LogInformation("添加商品信息成功");
                return Task.FromResult(res);
            }
            else
            {
                res.Msg= "添加商品信息失败";
                res.Code = APIEnums.Fail;
                res.Data = r;
                logger.LogInformation("添加商品信息失败");
                return Task.FromResult(res);
            }
        }
    }
}
